package com.wangsh.splider.system.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.pojo.JSONEnum;
import com.wangsh.splider.common.service.BaseServiceImpl;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.common.util.ExecutorServiceUtil;
import com.wangsh.splider.common.util.PageInfoUtil;
import com.wangsh.splider.orders.pojo.AOrdersClient;
import com.wangsh.splider.orders.service.IOrdersDbService;
import com.wangsh.splider.system.dao.IASysCountryDao;
import com.wangsh.splider.system.dao.IASysIpDao;
import com.wangsh.splider.system.dao.IASysProxyDao;
import com.wangsh.splider.system.pojo.ASysClient;
import com.wangsh.splider.system.pojo.ASysClientEnum;
import com.wangsh.splider.system.pojo.ASysCountry;
import com.wangsh.splider.system.pojo.ASysIp;
import com.wangsh.splider.system.pojo.ASysIpEnum;
import com.wangsh.splider.system.pojo.ASysMailAccount;
import com.wangsh.splider.system.pojo.ASysProxy;
import com.wangsh.splider.system.pojo.ASysProxyEnum;
import com.wangsh.splider.system.pojo.ASysWebUrl;
import com.wangsh.splider.system.service.ISystemOperService;
import com.wangsh.splider.system.service.ISystemDbService;
import com.wangsh.splider.task.pojo.ATaskDesc;
import com.wangsh.splider.task.pojo.ATaskDescEnum;
import com.wangsh.splider.task.pojo.ATaskUsers;
import com.wangsh.splider.task.pojo.ATaskUsersEnum;
import com.wangsh.splider.task.service.ITaskDbService;
import com.wangsh.splider.util.ServiceCallableUtil;

/**
 * 操作的实现类
 * 
 * @author TeaBig
 */
 
@Service("systemOperService")
public class SystemOperServiceImpl extends BaseServiceImpl implements ISystemOperService
{
	@Resource
	private ISystemDbService systemDbService;
	@Resource
	private IASysIpDao sysIpDao;
	@Resource
	private IASysCountryDao sysCountryDAO;
	@Resource
	private IASysProxyDao sysProxyDao;
	@Resource
	private ITaskDbService taskDbService;
	@Resource
	private IOrdersDbService orderSercice;
	@Resource
	private ISystemOperService systemOperService;

	@Override
	public ApiResponse<ASysCountry> operUpdateBatchCountryService(Map<String, Object> condMap)
	{
		ApiResponse<ASysCountry> apiResponse = new ApiResponse<ASysCountry>();
		condMap.put("key", JSONEnum.ID.getStatus());
		try
		{
			int res = this.sysCountryDAO.updateBatch(condMap);
			if (res > 0)
			{
				apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			} else
			{
				apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
			}
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
		}
		return apiResponse;
	}

	@Override
	public ApiResponse<ASysIp> operFindIp(String ip) 
	{
		ApiResponse<ASysIp> apiResponse = new ApiResponse<ASysIp>();
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("ip", ip);
		try 
		{
			apiResponse = this.systemDbService.findOneSysIpService(condMap);
			// 查询这个ip数据 如果不等于null就说明在数据库查到了 ，直接返回输出
			if (apiResponse.getDataOneJava() == null) {
				/**
				 **  如果数据库没查到 就要把这个ip的数据存到数据库
				 ** 先查询淘宝，如果淘宝没查到那就去ip138里面查
				 */
				Map<String, String> headerMap = new HashMap<String, String>();
				JSONObject responseJSON = this.jsoupUtil.ipLocation(ip, headerMap);
				/* 说明查询到数据了 */
				if(responseJSON != null && "0".equalsIgnoreCase(responseJSON.get("code") + ""))
				{
					JSONObject dataResJson = responseJSON.getJSONObject("data");
					ASysIp sysip = new ASysIp();
					if(!"".equalsIgnoreCase(dataResJson.getString("country_id")))
					{
						condMap.clear();
						condMap.put("engName", dataResJson.getString("country_id"));
						ApiResponse<ASysCountry> CountryResponse = this.systemDbService.findOneCountryService(condMap);
						if (CountryResponse.getDataOneJava() != null)
						{
							sysip.setCountryId(CountryResponse.getDataOneJava().getId());
						} 
					}else
					{
						/* 根据名字查询,国家 */
						condMap.clear();
						condMap.put("nameLike", "%" + dataResJson.getString("country") + "%");
						ApiResponse<ASysCountry> countryResponse = this.systemDbService.findOneCountryService(condMap);
						ASysCountry country = countryResponse.getDataOneJava() ;
						if (country != null)
						{
							sysip.setCountryId(country.getId());
							dataResJson.put("country_id", country.getEngName());
						} 
						
					}
					sysip.setName(dataResJson.getString("ip"));
					sysip.setIp(dataResJson.getString("ip"));
					sysip.setIpStr(dataResJson.getString("country") + "-" + dataResJson.getString("region") + "-"
							+ dataResJson.getString("city"));
					sysip.setIsp(dataResJson.getString("isp"));
					sysip.setResponse(responseJSON.toJSONString());
					sysip.setStatus(ASysIpEnum.STATUS_ENABLE.getStatus());
					sysip.setContent(dataResJson.getString("allInfo"));
					sysip.setPubTime(new Date());
	
					ApiResponse<Object> a = this.systemDbService.saveOneSysIpService(sysip);
	
					condMap.clear();
					condMap.put("ip", sysip.getIp());
					apiResponse = this.systemDbService.findOneSysIpService(condMap);
				}
			}
		} catch (Exception e) {
			ConstatFinalUtil.SYS_LOGGER.error("查询一条记录失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			// 报错信息的占位符
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);			
		}
		return apiResponse;
	}
		

	/**
	 * 根据国家查询一条ip代理
	 * 
	 * @param type
	 * @param country 这是一个集合(可以根据status,id,countryId,ipId,ip)进行查询
	 * @return
	 */
	@Override
	public ApiResponse<ASysProxy> operFindOneSysProxyByCountry(Map<String, Object> condMap)
	{
		ApiResponse<ASysProxy> apiResponse = new ApiResponse<ASysProxy>();
		Map<String, ASysProxy> data = new HashMap<String, ASysProxy>();
		try
		{
			condMap.put("status", ASysProxyEnum.STATUS_USE.getStatus());
			apiResponse = this.systemDbService.findOneSysProxyService(condMap);
			ASysProxy sysProxy = apiResponse.getDataOneJava();
			if (sysProxy != null)
			{
				Date souDate = sysProxy.getPubTime() ; 
				sysProxy.setPubTime(new Date());
				this.systemDbService.updateOneSysProxyService(sysProxy);
				sysProxy.setPubTime(souDate);
			}
			data.put(ApiResponseEnum.NAME_ONE.getName(), sysProxy);
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			/* 将结果放到JSON中 */
			apiResponse.setDataOne(data);
			apiResponse.setDataOneJava(sysProxy);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("查询一条记录失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
		}
		return apiResponse;
	}

	@Override
	public ASysProxy operSaveOneSysProxy(Map<String, Object> proxy)
	{
		Map<String, Object> extMap = new HashMap<String, Object>();
		String ip = "";
		if (proxy.get("ip") != null)
		{
			ip = proxy.get("ip") + "";
		}
		String country = "";
		if (proxy.get("country") != null)
		{
			country = proxy.get("country") + "";
		}
		String port = "";
		if (proxy.get("port") != null)
		{
			port = proxy.get("port") + "";
		}
		ASysIp sysIpResTar = null;
		/* 切换IP */
		for (int i = 0; i < ConstatFinalUtil.REQ_COUNT; i++)
		{
			sysIpResTar = operSwitchIpSysProxyUtil(ip, country);
			ConstatFinalUtil.SYS_LOGGER.info("切换ip:次数:{},结果:{}", i, sysIpResTar);
			if (sysIpResTar != null)
			{
				break;
			}
		}
		if(sysIpResTar != null)
		{
			/* 根据ip查询代理 */
			extMap.clear();
			extMap.put("ipId", sysIpResTar.getId());
			ApiResponse<ASysProxy> apiResponseRes = this.systemDbService.findOneSysProxyService(extMap);
			ASysProxy sysProxy = apiResponseRes.getDataOneJava();
			if (sysProxy == null)
			{
				sysProxy = new ASysProxy();

				// 设置国家id
				sysProxy.setCountryId(sysIpResTar.getCountryId());
				// 设置ipid
				sysProxy.setIpId(sysIpResTar.getId());
				sysProxy.setIp(sysIpResTar.getIp());
				sysProxy.setPort(port);
				sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
				sysProxy.setSuccedNum(sysProxy.getSuccedNum() + 1);
				sysProxy.setStatus(ASysProxyEnum.STATUS_USE.getStatus());
				/* 为对象赋值 */
				sysProxy.setRandInt(UUID.randomUUID().variant());
				sysProxy.setPubTime(new Date());
				sysProxy.setCreateTime(new Date());
				sysProxy.setUpdateTime(new Date());
				/* 保存结果 */
				ApiResponse<Object> response = this.systemDbService.saveOneSysProxyService(sysProxy);
				ConstatFinalUtil.SYS_LOGGER.info("--ip-代理添加返回结果:{}--", response.toJSON());
			}
			return sysProxy ; 
		}
		return null;

	}

	private ASysIp operSwitchIpSysProxyUtil(String ip, String country)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据国家简写查询国家 */
		condMap.clear();
		condMap.put("engName", country);
		ApiResponse<ASysCountry> countryApiResponse = this.systemDbService.findOneCountryService(condMap);
		ASysCountry sysCountry = countryApiResponse.getDataOneJava() ; 
		
		/*
		 * 切换ip,检查切换的ip是否正确 会存在切换ip以后,无法上网的上线,需要等待一下
		 */
		/* 先查询本机,看看本机的ip是否和想要切换的ip一样,如果一样,就不用切换 */
		// -传入字符串""
		ApiResponse<ASysIp> sysIpApiResponse = this.operFindIp("");
		ASysIp sysIpRes = sysIpApiResponse.getDataOneJava();
		boolean switchFlag = false;
		/* 随机找的国家代理 */
		ASysProxy sysProxy = null;

		/*
		 * 思路 如果ip要是存在,直接切回指定ip 如果ip不存在,直接按照国家重新生成一个
		 */
		if (sysIpRes != null)
		{
			/* 判断ip */
			if (!"".equalsIgnoreCase(ip))
			{
				/* 要切换ip */
				if (!ip.equalsIgnoreCase(sysIpRes.getIp()))
				{
					/* ip和本机不一样,尝试切换Ip */
					switchFlag = this.commandUtil.switchIp(ip, "");
					switchFlag = true;
				} else
				{
					/* 期望的ip和本机ip一样,直接返回 */
					return sysIpRes ; 
				}
			}
			
			/* 如果ip定位的国家和传入的国家一样,不用切换ip,肯定不一样 */
			if(!switchFlag && country.equalsIgnoreCase(sysIpRes.getCountry().getEngName()))
			{
				/* 根据ip查询代理 */
				condMap.clear();
				condMap.put("ipId", sysIpRes.getId());
				ApiResponse<ASysProxy> sysProxyApiResponse = this.operFindOneSysProxyByCountry(condMap);
				sysProxy = sysProxyApiResponse.getDataOneJava();
				/* 如果当前的ip在系统中可以找到;(不能请求facebook长时间使用同一个ip,所以需要切换);
				 * 在指定时间内可以使用同一个ip
				 */
				long currLong = System.currentTimeMillis();
				/* 指定的时间 */
				long defLong = Long.valueOf(ConstatFinalUtil.CONFIG_JSON.getString("system.proxy.timeout"))
						* ConstatFinalUtil.SECOND;
				if (sysProxy != null && currLong - sysProxy.getPubTime().getTime() < defLong)
				{
					sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
					sysProxy.setSuccedNum(sysProxy.getSuccedNum() + 1);
					sysProxy.setPubTime(new Date());
					this.systemDbService.updateOneSysProxyService(sysProxy);
					return sysIpRes ; 
				}
			}
		}
		
		/* 国家 */
		if (!switchFlag && !"".equalsIgnoreCase(country))
		{
			/* 要切换国家 
			    TODO 优先选择去数据库里面找一个已经存在的ip
			 *  *如果911切换失败, ~木有费了,需要找以前的ip进行切换
			 */
			condMap.clear();
			condMap.put("countryId", sysCountry.getId());
			ApiResponse<ASysProxy> sysProxyApiResponse = this.operFindOneSysProxyByCountry(condMap);
			sysProxy = sysProxyApiResponse.getDataOneJava();
			
			/*
			 * 如果系统代理不为空,并且最早的时间和现在的时间相比,在指定的时间以空,说明太频繁了,需要更新一个新的国家代理
			 * 否则可以使用系统数据库中生成的,找到指定的ip进行代理,就可以
			 * 
			 * 短期内不能使用同一个ip,必须在指定时间之外才能使用同一个ip
			 */
			long currLong = System.currentTimeMillis();
			/* 指定的时间 */
			long defLong = Long.valueOf(ConstatFinalUtil.CONFIG_JSON.getString("system.proxy.timeout"))
					* ConstatFinalUtil.SECOND;
			if (sysProxy != null && currLong - sysProxy.getPubTime().getTime() > defLong)
			{
				/* ip和本机不一样,尝试切换Ip */
				switchFlag = this.commandUtil.switchIp(sysProxy.getIp(), "");
			} else
			{
				/* 根据国家切换ip */
				switchFlag = this.commandUtil.switchIp("", country);
			}
			switchFlag = true;
		}
		
		/*
		 * 切换成功 切换是否成功,通过iptao来验证
		 */
		if (switchFlag)
		{
			/* 切换之后,再查询一次,是否切换成功 */
			sysIpApiResponse = this.operFindIp("");
			ASysIp sysIpResTar = sysIpApiResponse.getDataOneJava();
			/* 如果ip不为空,那就可以切换成功,并且切换后的ip和原来的一样,就可以 */
			if (sysIpResTar == null)
			{
				/* 说明查询ip,淘宝失败了,或者当前ip不可以用 */
				if (sysProxy != null)
				{
					/* 说明是从数据库中找的国家代理 */
					sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
					sysProxy.setFailedNum(sysProxy.getFailedNum() + 1);
					sysProxy.setPubTime(new Date());
					this.systemDbService.updateOneSysProxyService(sysProxy);
				}
				return null;
			} else if (!"".equalsIgnoreCase(ip) && sysIpResTar.getIp().equalsIgnoreCase(ip))
			{
				/* 说明查询ip,淘宝失败了,或者当前ip可以用 */
				if (sysProxy != null)
				{
					sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
					sysProxy.setSuccedNum(sysProxy.getSuccedNum() + 1);
					sysProxy.setPubTime(new Date());
					this.systemDbService.updateOneSysProxyService(sysProxy);
				}
				return sysIpResTar;
			} else if (!"".equalsIgnoreCase(country) && sysIpResTar.getCountry().getEngName().equalsIgnoreCase(country))
			{
				/* 说明查询ip,淘宝失败了,或者当前ip可以用 */
				if (sysProxy != null)
				{
					sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
					sysProxy.setSuccedNum(sysProxy.getSuccedNum() + 1);
					sysProxy.setPubTime(new Date());
					this.systemDbService.updateOneSysProxyService(sysProxy);
				}
				/* 要切换国家 */
				return sysIpResTar;
			} else
			{
				/* 说明查询ip,淘宝失败了,或者当前ip不可以用 */
				if (sysProxy != null)
				{
					/* 说明是从数据库中找的国家代理 */
					sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
					sysProxy.setFailedNum(sysProxy.getFailedNum() + 1);
					sysProxy.setPubTime(new Date());
					this.systemDbService.updateOneSysProxyService(sysProxy);
				}
				return null;
			}
		}
		/* 压根就切换失败了 */
		if (sysProxy != null)
		{
			/* 说明是从数据库中找的国家代理 */
			sysProxy.setTotalNum(sysProxy.getTotalNum() + 1);
			sysProxy.setFailedNum(sysProxy.getFailedNum() + 1);
			sysProxy.setPubTime(new Date());
			this.systemDbService.updateOneSysProxyService(sysProxy);
		}
		return null;
	}

	@Override
	public ApiResponse<ASysProxy> operReadFileSavaSysProxy(String countryName)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		Map<String, Object> condMap = new HashMap<String, Object>();
		Map<String, String> headerMap = new HashMap<String, String>();
		Map<String, String> paramsMap = new HashMap<String, String>();
		Map<String, String> responseMap = new HashMap<String, String>();
		try
		{
			// 文件夹路径
			String path = "G:\\proxy";
			File file = new File(path);
			// 获取文件夹下所有的文件
			File[] listFiles = file.listFiles();
			int num = 0;
			boolean returnb = false;
			for (int i = 0; i < listFiles.length; i++)
			{
				FileInputStream is = new FileInputStream(listFiles[i]);
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String line = "";
				String ip = "";
				String port = "";
				while ((line = bufferedReader.readLine()) != null)
				{
					if (countryName != null && !"".equals(countryName))
					{
						num++;
						String[] split = line.split("@");
						String country = "";
						if (split.length>=2)
						{
							String lastSplit = split[1];
							String[] split2 = lastSplit.split("\\$");
							if (split2.length>=2)
							{
								String lastSplit2 = split2[1];
								String[] split3 = lastSplit2.split(" ");
								country = split3[0];
							}
							if (countryName.contains(country))
							{
								// 根据 @ 分两部分 0为前半部分
								String firstSplit = split[0];
								// 如果前半部分有值
								if (firstSplit != null && !"".equals(firstSplit))
								{
									ASysProxy sysProxy = new ASysProxy();
									// 根据: 分两部分 index为0ip,index为1端口
									String[] firstlastSplit2 = firstSplit.split(":");
									if (firstlastSplit2.length < 1)
									{
										apiResponse.setInfo("获取数据异常", null);
									} else
									{
										ip = firstlastSplit2[0];
										port = firstlastSplit2[1];

										condMap.put("ip", ip);
										// 查看这个ip是否已经保存
										ApiResponse<ASysProxy> findOneSysProxyService = systemDbService
												.findOneSysProxyService(condMap);
										if (findOneSysProxyService.getDataOneJava() == null)
										{
											ApiResponse<ASysIp> sysIpResponse;
											try
											{
												// 担心他报异常会导致 存空数据
												sysIpResponse = operFindIp(ip);
												ASysIp sysIp = sysIpResponse.getDataOneJava();
												if (split[1] != null && !"".equals(split[1]))
												{
													sysProxy.setContent(split[1]);
												}
												proxySave(ip, port, sysProxy, sysIp);
												ApiResponse<Object> saveOneSysProxyService = systemDbService
														.saveOneSysProxyService(sysProxy);
												ConstatFinalUtil.SYS_LOGGER.info("保存ip代理成功：{}", saveOneSysProxyService.toJSON());
												condMap.clear();
												condMap.put("id",saveOneSysProxyService.getDataOne().get("id"));
												ApiResponse<ASysProxy> findOneSysProxyService2 = systemDbService.findOneSysProxyService(condMap);
												return findOneSysProxyService2;
												//Thread.sleep(7000);
											} catch (Exception e)
											{
												ConstatFinalUtil.SYS_LOGGER.error("请求淘宝失败了", e);
												apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
												Map<String, String> infoMap = new HashMap<String, String>();
												/* 报错信息的占位符 */
												infoMap.put("errinfo", e.toString());
												apiResponse.setInfo(
														ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
												continue;
											}
										} else
										{
											apiResponse.setInfo("数据已存在 by:" + ip + ":" + port, Collections.EMPTY_MAP);
										}
										

									}

								} else
								{
									apiResponse.setInfo("获取的数据为空,请检查", null);
									continue;
								}
								// 读取文件的while结束
								ConstatFinalUtil.SYS_LOGGER.info("info:{},第{}次", apiResponse.getInfo(), num);
							}
						}
						
					}
				}
				// 文件路径的fou结束
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
		}
		return null;
	}

	// 暂时先放这 不行就删，先放这主要是为了看着方便一点 上面代码太多 看着难受
	private void proxySave(String ip, String port, ASysProxy sysProxy, ASysIp sysIp)
	{
		sysProxy.setIp(ip);
		sysProxy.setIpId(sysIp.getId());
		sysProxy.setCountryId(sysIp.getCountryId());
		sysProxy.setPort(port);
		sysProxy.setProxyType(0);
		sysProxy.setRandInt(0);
		sysProxy.setStatus(Byte.valueOf("1"));
		sysProxy.setPubTime(new Date());
		sysProxy.setCreateTime(new Date());
		sysProxy.setUpdateTime(new Date());
	}

	/**
	 * 随机从数据库中选择账号 发送邮件的方法（单个或者多个）
	 * @param email 发送的账号
	 * @param text 
	 * @param subject
	 */
	@Override
	public ApiResponse<Object> operSendEmail(ASysMailAccount sysMailAccount,String email,String text,String subject)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		if(sysMailAccount == null)
		{
			Map<String, Object> condMap =new HashMap<String, Object>();
			condMap.put("pubTime", "");
			ApiResponse<ASysMailAccount> apiResponse2 = this.systemDbService.findOneMailAccountService(condMap);
			Map<String, ASysMailAccount> dataOne = apiResponse2.getDataOne();
			sysMailAccount = dataOne.get(ApiResponseEnum.NAME_ONE.getName());
		}
		
		sysMailAccount.setPubTime(new Date());
	    String host=sysMailAccount.getHost();
		String username=sysMailAccount.getUserName();
		String password=sysMailAccount.getPassword();
		boolean sendTextMail = springEmailUtil.sendHTMLMail(host, username, password, email, subject, text);
	    if(sendTextMail)
	    {
	    	sysMailAccount.setTotalNum( sysMailAccount.getTotalNum()+1);
	    	sysMailAccount.setSuccedNum(sysMailAccount.getSuccedNum()+1);
	    	sysMailAccount.setSendTime(new Date());
	    	sysMailAccount.setUpdateTime(new Date());
	    }else
	    {
	    	sysMailAccount.setTotalNum( sysMailAccount.getTotalNum()+1);
	    	sysMailAccount.setFailedNum(sysMailAccount.getFailedNum()+1);
	    	sysMailAccount.setTodayFailedNum(sysMailAccount.getTodayFailedNum()+1);
	    }
		apiResponse = this.systemDbService.updateOneMailAccountService(sysMailAccount);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + "") + ";发送标识:" + sendTextMail,
				Collections.EMPTY_MAP);
		return apiResponse;
	}

	/**
	 * 多个账号随机发送邮件，一个账号可以给两个用户发送邮件(用户数量可以更改)
	 */
	@Override
	public void operSendMoreEmail(List<ATaskUsers> usersList,String taskId)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		/* 清空数据 */
		condMap.clear();
		/* 根据邮箱账户Id,查询发送邮箱的账户 */
		condMap.put("id", taskId); 
		ApiResponse<ATaskDesc> taskDescApiResponse = this.taskDbService.findOneDescService(condMap);
		ATaskDesc taskDesc = taskDescApiResponse.getDataOneJava();
		/* 任务描述 */
		String content = taskDesc.getContent();
		String subject = taskDesc.getName() ; 
		JSONObject contentParamJSON = taskDesc.getContentParamJSON() ; 
		
		/* --查询最近更新的邮箱账户-- */
		condMap.clear();
		condMap.put("pubTime", "");
		ApiResponse<ASysMailAccount> mailAccountApiResponse = this.systemDbService.findOneMailAccountService(condMap);
		ASysMailAccount account = mailAccountApiResponse.getDataOneJava();
		/* 获取账号的信息 */
		String host = account.getHost() ; 
		String username = account.getUserName() ; 
		String password = account.getPassword() ; 
		
		/* 随机数 */
		Random random = new Random();
		for (Iterator iterator = usersList.iterator(); iterator.hasNext();)
		{
			ATaskUsers taskUsers = (ATaskUsers) iterator.next();
			String email = taskUsers.getEmail() ; 
			
			/* 只有状态为未发送的,才会发送 */
			if(taskUsers.getStatus() == ATaskUsersEnum.STATUS_WITHDRAWALORDER.getStatus())
			{
				
				/* 更改为发送中 */
				taskUsers.setStatus(ATaskUsersEnum.STATUS_WITHDRAWALORDER.getStatus());
				
				/* 将发送的内容修改一下 */
				contentParamJSON.put("email", email);
				/* 生成随机的内容 */
				int randInt = random.nextInt(50);
				String randStr = this.regexUtil.randStr(randInt);
				contentParamJSON.put("randStr", randStr);
				
				Map<String, String> emailParamMap = ConstatFinalUtil.jsonToMap(contentParamJSON);
				/* 替换邮件内容 */
				content = this.fileUtil.replaceOperator(content, emailParamMap);
				
				boolean sendTextMail = springEmailUtil.sendHTMLMail(host, username, password, email, subject, content);
				if (sendTextMail)
				{
					account.setTotalNum(account.getTotalNum() + 1);
					account.setSuccedNum(account.getSuccedNum() + 1);
					account.setSendTime(new Date());
					account.setUpdateTime(new Date());
					account.setPubTime(new Date());
					
					taskUsers.setStatus(ATaskUsersEnum.STATUS_PENDINGORDER.getStatus());
					taskUsers.setUpdateTime(new Date());
					taskUsers.setMailName(username);
				} else
				{
					account.setTotalNum(account.getTotalNum() + 1);
					account.setFailedNum(account.getFailedNum() + 1);
					account.setTodayFailedNum(account.getTodayFailedNum() + 1);
					
					taskUsers.setStatus(ATaskUsersEnum.STATUS_COMPLETEDORDER.getStatus());
				}
			}
			// 发送成功或者失败都要对数据库中数据进行修改
			this.taskDbService.updateOneUsersService(taskUsers);
			/* 线程随机休眠 */
			ConstatFinalUtil.randSleep("slow");
		}
		/* 每当发送完一页的邮件时,更新邮箱的账户信息 */
		this.systemDbService.updateOneMailAccountService(account);
		ConstatFinalUtil.SYS_LOGGER.info("邮件总数:{},账户id:{},账户邮箱:{}",usersList.size(),account.getId(),account.getUserName());
	}
	
	/**
	 * 查询所有未发送的邮箱,查询一次,开启一个线程
	 */
	@Override
	public boolean operUsersSendMailService(String taskId)
	{
		Random random = new Random();
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		
		Map<String, Object> condMap =new HashMap<String, Object>();
		 /* 100条以内,随机 */
		pageInfoUtil.setPageSize(random.nextInt(20) + 1);
		
		/* 清空数据 */
		condMap.clear();
		/* 根据邮箱账户Id,查询发送邮箱的账户 */
		condMap.put("id", taskId); 
		ApiResponse<ATaskDesc> taskDescApiResponse = this.taskDbService.findOneDescService(condMap);
		ATaskDesc taskDesc = taskDescApiResponse.getDataOneJava();
		
		while(true)
		{
			// 防止一个人发两次 默认是desc降序
			condMap.clear();
			//可以根据任务的id查找任务用户表中相对应任务id的用户
			condMap.put("taskId", taskId);
			condMap.put("status", ATaskUsersEnum.STATUS_NOTSTARTED.getStatus() + "");
			/* 查询要发送的邮箱 */
			ApiResponse<ATaskUsers> usersApiResponse = this.taskDbService.findCondListUsersService(pageInfoUtil, condMap);
			List<ATaskUsers> usersList = usersApiResponse.getDataListJava();
			if(usersList.size() == 0 )
			{
				/* 已经发送完成,更新任务状态 */
				taskDesc.setStatus(ATaskDescEnum.STATUS_ACCOMPLISH.getStatus());
				taskDesc.setUpdateTime(new Date());
				this.taskDbService.updateOneDescService(taskDesc);
				break ; 
			}
			for (Iterator iterator = usersList.iterator(); iterator.hasNext();)
			{
				ATaskUsers taskUsers = (ATaskUsers) iterator.next();
				/* 修改状态 */
				taskUsers.setStatus(ATaskUsersEnum.STATUS_WITHDRAWALORDER.getStatus());
				taskUsers.setUpdateTime(new Date());
				this.taskDbService.updateOneUsersService(taskUsers);
			}
			
			/* 多线程发送 */
			ServiceCallableUtil serviceCallableUtil=new ServiceCallableUtil();
			String operType="sendMoreEmail";
			Map<String, Object> paramsMap =new HashMap<String,Object>();
			paramsMap.put("systemOperService", systemOperService);
			paramsMap.put("taskId",  taskId + "");
			paramsMap.put("usersList", usersList);
			serviceCallableUtil.setOperType(operType);
			serviceCallableUtil.setParamsMap(paramsMap);
			
			try {
				ExecutorServiceUtil.submit(serviceCallableUtil);
			} catch (Exception e) {
				return false;
			}
			/* 线程随机休眠 */
			ConstatFinalUtil.randSleep("slow");
		}
		return true;
	}
	
	
	@Override
	public ApiResponse<ASysClient> operRtOneClient(Map<String, Object> condMap)
	{
		ApiResponse<ASysClient> apiResponse = new ApiResponse<ASysClient>();
		condMap.put("status", ASysClientEnum.STATUS_DISABLE.getStatus());
		condMap.put("pubTimeDesc", 1);
		apiResponse = this.systemDbService.findOneClientService(condMap);
		ASysClient dataOneJava = apiResponse.getDataOneJava();
		dataOneJava.setPubTime(new Date());
		this.systemDbService.updateOneClientService(dataOneJava);
		return apiResponse;
	}

	@Override
	public JSONArray operOrderRead(Map<String, Object> condMap, ASysWebUrl sysWebUrl)
	{
		// ApiResponse<ASysWebUrl> apiResponse = new ApiResponse<ASysWebUrl>();
		// apiResponse = this.systemService.findOneWebUrlService(condMap);
		// ASysWebUrl weburl = apiResponse.getDataOneJava();
		// 限制条数用
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		pageInfoUtil.setPageSize(sysWebUrl.getHeaderNum());
		condMap.put("orderBy", "pubTimeAsc");
		condMap.put("souType", sysWebUrl.getSouType() + "");
		ApiResponse<AOrdersClient> orderClientList = orderSercice.findCondListClientService(pageInfoUtil, condMap);
		List<AOrdersClient> orderClients = orderClientList.getDataListJava();
		if (orderClients == null)
		{
			return new JSONArray();
		}
		// 返回的结果
		JSONArray jsonArr = new JSONArray();
		for (AOrdersClient ordersClient : orderClients)
		{
			JSONObject jsonOb = new JSONObject();
			ordersClient.setPubTime(new Date());
			// 根据pubTime获取,把pubTIme设置为最新的下次就不会再获取到
			orderSercice.updateOneClientService(ordersClient);
			// 获取参数
			String cookie = ordersClient.getCookieClient();
			String source = ordersClient.getHttpSource();
			JSONObject parse = (JSONObject) JSON.parse(source);
			JSONObject object = (JSONObject) parse.get("request");
			String userAgent = (String) object.get("user-agent");
			// 存储参数
			jsonOb.put("cookie", cookie);
			jsonOb.put("user-agent", userAgent);
			jsonArr.add(jsonOb);
		}
		return jsonArr;
	}

	@Override
	public ApiResponse<Object> operSaveClient(JSONObject clientJson)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--operSaveClient--");
		ApiResponse<Object> response = new ApiResponse<Object>();
		ASysClient client = new ASysClient();
		// 获取ip和端口号
		String ip = clientJson.get("ip").toString();
		String port = clientJson.get("port").toString();
		if (ip == null || "".equals(ip))
		{
			return new ApiResponse<Object>();
		}
		JSONObject data = clientJson.getJSONObject("data");
		/* 服务器类型:0:客户端,1:服务器 */
		String clientType = data.getString("clientType");
		if(clientType == null)
		{
			clientType = ASysClientEnum.SOURCETYPE_SERVER.getStatus() + ""; 
		}
		int failedNum = 0;
		int succedNum = 0;
		int totalNum = 0;
		int todayFailedNum = 0;
		int todaySuccedNum = 0;
		int todayTotalNum = 0;
		// 先根据ip查询到这个ip的所属id
		Map<String, Object> condMap = new HashMap<String, Object>();
		// 再根据这个ipId查到指定的用户
		condMap.put("ip", ip);
		ApiResponse<ASysIp> sysIpApi = systemDbService.findOneSysIpService(condMap);
		int ipId = 0;
		int countryId = 0;
		// 如果为null 代表 ip表中没有这个ip 就保存
		if (sysIpApi.getDataOneJava() == null)
		{
			// 查询ip在数据库中是否存在和所属国家
			ApiResponse<ASysIp> operFindIp = this.operFindIp(ip);
			if (operFindIp.getDataOneJava() == null)
			{
				return new ApiResponse<Object>();
			}
			ipId = operFindIp.getDataOneJava().getId();
			countryId = operFindIp.getDataOneJava().getCountryId();
		} else
		{
			// 如果不为null 酒吧ipId已存 然后去看client表中是否存在有这个ipId的client就好
			ipId = sysIpApi.getDataOneJava().getId();
			countryId = sysIpApi.getDataOneJava().getCountryId();
		}
		condMap.clear();
		condMap.put("ipId", ipId);
		ApiResponse<ASysClient> sysClientApi = systemDbService.findOneClientService(condMap);
		ASysClient sysClient = sysClientApi.getDataOneJava();
		// 判断SysClient表中是否存在,添加不需要设置次数,因为添加记录的时候是获取不到记录的
		if (sysClient == null)
		{
			// 设置内容
			// 判断是否为服务器的ip 如果是就是服务端请求,
			// 这个地址得写到configJson,因为说不定会变
			if (clientType.equalsIgnoreCase(ASysClientEnum.SOURCETYPE_SERVER.getStatus() + ""))
			{
				client.setSourceType(ASysClientEnum.SOURCETYPE_SERVER.getStatus());
			} else
			{
				client.setSourceType(ASysClientEnum.SOURCETYPE_CLIENT.getStatus());
			}
			client.setIpId(ipId);
			client.setPort(port);
			client.setCountryId(countryId);
			client.setCreateTime(new Date());
			client.setPubTime(new Date());
			client.setUpdateTime(new Date());
			client.setAttackTime(new Date());
			client.setStatus(ASysClientEnum.STATUS_ATTACKING.getStatus());
			// 保存数据
			response = systemDbService.saveOneClientService(client);
			ConstatFinalUtil.SYS_LOGGER.info("保存后结果code:{},info:{}: ",response.getCode(),response.getInfo());
		} else
		{
			//如果data != null 代表开始保存用户的成功失败次数
			if (data != null && data.getInteger("totalNum") != null)
			{
				// 获取次数数据
				failedNum = data.getInteger("failedNum");
				succedNum = data.getInteger("succedNum");
				totalNum = data.getInteger("totalNum");
				todayFailedNum = data.getInteger("todayFailedNum");
				todaySuccedNum = data.getInteger("todaySuccedNum");
				todayTotalNum = data.getInteger("todayTotalNum");
				
				// 如果数据库中已经存在就直接更新
				sysClient.setPort(port);
				sysClient.setTotalNum(sysClient.getTotalNum() + totalNum);
				sysClient.setFailedNum(sysClient.getFailedNum() + failedNum);
				sysClient.setSuccedNum(sysClient.getSuccedNum() + succedNum);
				sysClient.setAttackTime(new Date());

				// 判断是否是今天true为今天
				Date updateTime = sysClient.getUpdateTime();
				SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
				String updateTimeStr = sf.format(updateTime);
				String now = sf.format(new Date());
				boolean equals = updateTimeStr.equals(now);
				if (equals)
				{
					sysClient.setTodayTotalNum(sysClient.getTodayTotalNum() + todayTotalNum);
					sysClient.setTodayFailedNum(sysClient.getTodayFailedNum() + todayFailedNum);
					sysClient.setTodaySuccedNum(sysClient.getTodaySuccedNum() + todaySuccedNum);
				} else
				{
					sysClient.setTodayTotalNum(todayTotalNum);
					sysClient.setTodayFailedNum(todayFailedNum);
					sysClient.setTodaySuccedNum(todaySuccedNum);
				}
				sysClient.setUpdateTime(new Date());
				response = systemDbService.updateOneClientService(sysClient);
				ConstatFinalUtil.SYS_LOGGER.info("更新后结果code:{},info:{}: ",response.getCode(),response.getInfo());
			}else {
				//else代表客户端进入了webUrlList并且他的ip已经存储在数据库了
				sysClient.setAttackTime(new Date());
				sysClient.setStatus(ASysClientEnum.STATUS_ATTACKING.getStatus());
				systemDbService.updateOneClientService(sysClient);
			}
		}
		return response;
	}
	
	@Override
	public void operJudgeClinetStatus()
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		// 获取状态为正在攻击并且时间最早的用户
		condMap.put("status", ASysClientEnum.STATUS_ATTACKING.getStatus());
		ApiResponse<ASysClient> AttackTimeMinClientApi = systemDbService.findOneClientByMinAttackService(condMap);
		ASysClient AttackTimeMinClient = AttackTimeMinClientApi.getDataOneJava();
		if (AttackTimeMinClient != null)
		{
			// 获取时间
			long AttackTimeMillis = AttackTimeMinClient.getAttackTime().getTime();
			long currentTimeMillis = System.currentTimeMillis();
			// long resultTimeHours = ((((currentTimeMillis -
			// AttackTimeMillis)/1000)/60)/60);
			long resultTimeHours = (((currentTimeMillis - AttackTimeMillis) / 1000)/60);
			// 如果该用户状态为正在攻击 但已经两小时都没有更新攻击状态的话 代表该用户已经停止攻击了
			if (resultTimeHours >= 1)
			{
				AttackTimeMinClient.setStatus(ASysClientEnum.STATUS_DISABLE.getStatus());
				systemDbService.updateOneClientService(AttackTimeMinClient);
			}
		}
		
	}

	@Override
	public void operJudgeClinetStatusList()
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		//状态为正在攻击
		condMap.put("status", ASysClientEnum.STATUS_ATTACKING.getStatus());
		//查询时间在5分钟之前的用户
		condMap.put("attackTime",new Date(System.currentTimeMillis()-((1000*60)*5)) );
		ApiResponse<ASysClient> clientListApi = systemDbService.findCondListClientService(null,condMap);
		for (int i = 0; i < clientListApi.getDataListJava().size(); i++)
		{
			ASysClient aSysClient = clientListApi.getDataListJava().get(i);
			//五分钟都没有更新状态代表都没在攻击了呗,就算误报也有Judge接口让它变成启用
			aSysClient.setStatus(ASysClientEnum.STATUS_DISABLE.getStatus());
			systemDbService.updateOneClientService(aSysClient);
		}
	}
}